<template>
  <div>
    <van-row @click="openModal">
      <van-col span="6">
        <img :src="avatarSrc" alt="" />
      </van-col>
      <van-col span="10">{{nickName}}</van-col>
      <van-col span="8">
        <van-icon :name="ifLogined ? 'cross' : 'arrow'" @click="loginOut" />
      </van-col>
    </van-row>

    <van-grid square :column-num="3">
      <van-grid-item
        v-for="item in gridArr"
        :key="item.id"
        :icon="item.icon"
        :text="item.type"
        @click="gridItemClick"
      />
    </van-grid>

    <div class="login_modal" v-if="showModal">
      <section  @click="closeModal"></section>
      <van-form @submit="onSubmit">
        <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
          >提交</van-button>
      </div>
      <div class="form_bottom">没有账号,自动注册</div>  
    </van-form>
    </div>
  </div>
</template>

<script>
import { GoLogin } from '../request/api'
export default {
  name: "User",
  data() {
    return {
      // 模态框的显示隐藏
      showModal: false,
      avatarSrc: require("../assets/avatar.png"),
      username: '陈博华',
      password: '123456',
      // 昵称
      nickName: '点击登录',
      // 判断用户是否登录
      ifLogined: false,
      // grid数组
      gridArr: [
        { id: 0, icon: "label-o", type: "我的订单" },
        { id: 1, icon: "bill-o", type: "优惠券" },
        { id: 2, icon: "goods-collect-o", type: "礼品卡" },
        { id: 3, icon: "star-o", type: "我的收藏" },
        { id: 4, icon: "flag-o", type: "我的足迹" },
        { id: 5, icon: "contact", type: "会员福利" },
        { id: 6, icon: "location-o", type: "地址管理" },
        { id: 7, icon: "warn-o", type: "账号安全" },
        { id: 8, icon: "service-o", type: "联系客服" },
        { id: 9, icon: "question-o", type: "帮助中心" },
        { id: 10, icon: "smile-comment-o", type: "意见反馈" },
      ],
    }
  },
  methods: {
    onSubmit(val) {
      GoLogin({
        username: val['用户名'],
        pwd: val['密码']
      }).then(res => {
        if (res.errno == 0) {
          let { token, userInfo } = res.data;
          let newUserInfo = JSON.stringify(userInfo);
          localStorage.setItem('usertoken', token);
          localStorage.setItem('userInfo', newUserInfo);
          this.$toast.success('登录成功')
          // 修改用户的头像
          this.avatarSrc = userInfo.avatar
          // 修改用户的昵称
          this.nickName = userInfo.username
          // 设置用户登录状态
          this.ifLogined = true
          // 关闭模态框
          setTimeout(() => {
            this.closeModal()
          }, 1000)
          // 是否需要跳回上一页
          if (this.$store.state.ifgoBack) {
            // 显示即将回到上一页
            this.$toast.loading("即将回到上一页")
            // 要跳回上一页
            setTimeout(()=>{
              this.$router.back();
              // 顺手重新改为false
              this.$store.commit("changeIfgoBack", false);
            }, 1500)
          }
        } else {
          this.$toast.fail(res.errmsg)
        }
      })
    },
    // 打开模态框
    openModal() {
      let token = localStorage.getItem('usertoken')
      if (!token) {
        this.showModal = true
      }
    },
    // 关闭模态框
    closeModal() {
      this.showModal = false
    },
    // 退出登录
    loginOut() {
      if (this.ifLogined) {
        this.$dialog
          .confirm({
            title: "退出账号确认",
            message: "您是否想要退出当前账号？",
          })
          .then(() => {
            // 清除token
            localStorage.removeItem('usertoken')
            localStorage.removeItem('userInfo')
            // 刷新当前页面
            this.$router.go(0)
          })
          .catch(err => err)
      } else {
        // 会冒泡到父元素van-row上有打开模态框的点击事件，所以在这里不用在写了
        // 代表未登录，打开模态框
        // this.showModal = true
      }
    },
    gridItemClick() {
      let token = localStorage.getItem('usertoken')
      if (token) {
        this.$toast('该功能玩命开发中')
      } else {
        this.$toast('您还未登录')
      }
      
    }
  },
  created() {
    // 每次进入user页面，就直接判断有没有token，如果有就获取userInfo来渲染头像和昵称
    let token = localStorage.getItem('usertoken')
    if (token) {
      let userInfo = localStorage.getItem('userInfo')
      let newUserInfo = JSON.parse(userInfo)
      this.avatarSrc = newUserInfo.avatar
      this.nickName = newUserInfo.username
      this.ifLogined = true
    }
  }
}
</script>

<style lang="less" scoped>
.van-row {
  padding: 0.2rem 4%;
  background-color: #333;
  // background: #410303;
  color: #fff;
  .van-col {
    line-height: 0.7rem;
    font-size: 0.15rem;
    img {
      width: 0.7rem;
      border-radius: 50%;
      display: block;
    }
    &:last-child {
      text-align: right;
    }
  }
}

.login_modal {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
  section {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .van-form {
    width: 90%;
    height: 205px;
    position: absolute;
    top: 35vh;
    left: 50%;
    margin-left: -45%;
    padding: .1rem;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 3%;
    .van-button {
      background-color: darkred;
      border: 0;
    }
  }
}
.form_bottom {
  text-align: center;
  color: #ccc;
}
</style>